package com.ynet.middleground.approve.listener;

import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.approve.constant.WorkflowConstants;

/**
 * @author liulx
 * @description 监听器设置任务审批人, 任务人从流程变量参数里获取 <br />
 *              变量名规则: <br />
 *              设置审批人: listener_set_user <br />
 *              设置审批候选人列表: listener_set_calidate_users <br />
 *              设置审批候选组列表: listener_set_calidate_groups <br />
 *              <p>
 *              备用保留
 *              </p>
 * @date 2019-11-21 14:37
 */
@Component
public class SetTaskApproverListener implements TaskListener {

    @Override
    public void notify(DelegateTask delegateTask) {
        // 获取流程变量，流程变量通过渠道传递设置
        Map<String, Object> variables = delegateTask.getVariables();
        variables = Optional.ofNullable(variables).orElse(Maps.newHashMap());

        // 取出指定用户审批人变量 assignee
        Object assignee = variables.get(WorkflowConstants.LISTENER_SET_USER);
        Optional.ofNullable(assignee).ifPresent(u -> delegateTask.setAssignee(String.valueOf(u)));

        // 取出指定候选人列表, 多个以英文逗号隔开
        Object calidateUsers = variables.get(WorkflowConstants.LISTENER_SET_CANDIDATE_USERS);
        Optional.ofNullable(calidateUsers).ifPresent(u -> {
            List<String> calidateUserList =
                Stream.of(String.valueOf(calidateUsers).split(",")).collect(Collectors.toList());
            delegateTask.addCandidateUsers(calidateUserList);
        });

        // 取出指定候选用户组列表, 多个以英文逗号隔开
        Object calidateGroups = variables.get(WorkflowConstants.LISTENER_SET_CANDIDATE_GROUPS);
        Optional.ofNullable(calidateGroups).ifPresent(u -> {
            List<String> calidateGroupList =
                Stream.of(String.valueOf(calidateGroups).split(",")).collect(Collectors.toList());
            delegateTask.addCandidateGroups(calidateGroupList);
        });

        if (assignee == null && calidateUsers == null && calidateGroups == null) {
            throw new BusinessException("SetTaskApproverListener 监听器设置参数错误", "00001");
        }

    }

}
